using System.Threading;
using System.Collections;

using Microsoft.SPOT.Hardware;

using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.Hardware;

namespace CobraController
{
  class RF433
  {
    private static OutputCompare oc1;
    private const string onCode = "0F";
    private const string offCode = "F0";
    private static string FullCode;
    const int rfdelay = 400;  // Elro = 345
    const int rfRepeat = 3;
    private static ArrayList transmitstr = new ArrayList();
    private const FEZ_Pin.Digital RF433pin = FEZ_Pin.Digital.IO9;
    private static string systemcode;
    private static string unitcode;
    private static bool state;

    //public RF433(FEZ_Pin.Digital pin)
    //{
    //  RF433pin = pin;
    //}

    public static void SendCode(string SystemCode, string UnitCode, bool State)
    {
      systemcode = SystemCode;
      unitcode = UnitCode;
      state = State;

      new Thread(TransmitCode).Start();
    }

    private static void TransmitCode()
    {
      transmitstr.Clear();
      FullCode = string.Empty;

      FullCode = string.Concat(systemcode.ToUpper(), unitcode.ToUpper(), state ? onCode : offCode);

      for (int r = 0; r < rfRepeat; r++)
      {
        foreach (char x in FullCode)
        {
          switch (x)
          {
            case '0':
              transmitstr.Add(rfdelay);
              transmitstr.Add(3 * rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(3 * rfdelay);
              break;
            case 'F':
              transmitstr.Add(rfdelay);
              transmitstr.Add(3 * rfdelay);
              transmitstr.Add(3 * rfdelay);
              transmitstr.Add(rfdelay);
              break;
            case '1':
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              transmitstr.Add(rfdelay);
              break;
          }
        }

        transmitstr.Add(rfdelay);
        transmitstr.Add(32 * rfdelay);
      }

      uint[] tim = new uint[transmitstr.Count];
      for (int t = 0; t < transmitstr.Count; t++)
      {
        tim[t] = uint.Parse(transmitstr[t].ToString());
      }
      using (oc1 = new OutputCompare((Cpu.Pin)RF433pin, false, 50 * rfRepeat))
      {
        oc1.Set(true, tim, 0, tim.Length, false);
        Thread.Sleep(50 * rfRepeat);
      }

    }
  }
}
